package com.everflourish.yeah100.act.markingsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.SubjectAnswerAdapter;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.entity.marking.SubjectAnswer;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.ui.dialog.KeyboardWindow;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.AnswerUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.constant.StudentStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/10/25.
 * 时间：2016/10/25
 */
public class SubjectAnswerActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar mToolBar;
    public static Student mStudent;
    private ArrayList<SubjectAnswer> mList;
    private List<Topic> mTopics;
    private SubjectAnswerAdapter mAdapter;
    private GridView mStudentAnswerGv;
    private TextView mSaveTv;
    private TextView mHeaderScoreTv;
    private KeyboardWindow mPopupWindow;
    private int index;
    private TextView mStudentNameTv;
    private boolean isUpdate = false;
    public static LoadDialog mLoadDialog;
    private float mObjStudentScore;
    private float mSubTotalScore;// 主观题总分

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subject_answer);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mStudent = (Student) getIntent().getSerializableExtra(
                IntentUtil.STUDENT_ANSWER);
        mTopics = (List<Topic>) getIntent().getSerializableExtra(IntentUtil.TOPIC);
        setAnswerToList();
        mAdapter = new SubjectAnswerAdapter(mContext, SubjectAnswerActivity.this, mList);
        mSubTotalScore = AnswerUtil.getSubTotalScore2(mTopics);
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.toolbar_subject_answer);
        mSaveTv = (TextView) findViewById(R.id.subject_answer_save);
        mStudentNameTv = (TextView) findViewById(R.id.subject_student_name);
        mHeaderScoreTv = (TextView) findViewById(R.id.header_score);
        mStudentAnswerGv = (GridView) findViewById(R.id.subject_answer_gl);
        mStudentAnswerGv.setAdapter(mAdapter);
        mStudentAnswerGv.setOnItemClickListener(itemClickListener);
        mSaveTv.setOnClickListener(this);
    }

    private void configView() {
        mToolBar.setTitle("主观题分数");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
        mStudentNameTv.setText(mStudent.getName());
        setHeaderScore();
    }

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            showKeyboard(position);
        }
    };

    /**
     * 设置分数控件
     */
    private void setHeaderScore() {
        mObjStudentScore = 0f;
        for (int i = 0; i < mList.size(); i++) {
            mObjStudentScore += StringUtil.parseFloat(mList.get(i).getAnswer(), 0f);
        }
        mHeaderScoreTv.setText("(" + mObjStudentScore + "/" + mSubTotalScore
                + ")分");
    }

    /**
     * 把客观题字符串答案转为list
     */
    private void setAnswerToList() {
        String objectAnswer = mStudent.getAnswer().getSubjectAnswers();
        mList = AnswerUtil.answerSubOneList(objectAnswer, mTopics);
    }

    /**
     * 设置关闭activity的数据
     */
    private void finishMenuActivity() {
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.SINGLE_UPLOAD, isUpdate);
        MarkingMenuActivity.mFragmentReadPaper.isObjectOrSubjectInput = false;
        this.setResult(RESULT_OK, resultIntent);
        SubjectAnswerActivity.this.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.subject_answer_save:
                setStudentScore();
                break;
        }
    }

    private void setStudentScore() {
        if (!isUpdate) {
            MyToast.showShort(mContext, "答案没有修改");
            return;
        }
        if (isExceedScore()) {
            return;
        }
        String answerStr = AnswerUtil.listOneToAnswer(mList, mTopics, TopicUtil.getCurrentMaxNo(mTopics));
        mStudent.getAnswer().setSubjectAnswers(answerStr);
        float mSubStudentScore = 0f;
        for (int i = 0; i < mList.size(); i++) {
            mSubStudentScore += StringUtil.parseFloat(mList.get(i).getAnswer(), 0f);
        }
        mStudent.getAnswer().setSubjectScores(mSubStudentScore);
        // 上传
        mStudent.getAnswer().setPaperType("N");
        mStudent.setStatus(StudentStatus.I.text);
//        MarkingMenuActivity.mFragmentReadPaper.isChange = true;
        MarkingMenuActivity.mFragmentReadPaper.isObjectOrSubjectInput = true;
        mLoadDialog = LoadDialog.show(mContext, null, "正在保存...", false);
        MarkingMenuActivity.mFragmentReadPaper.uploadSingleStudentAnswerRequest(
                mStudent, true, "2", false);
    }

    private boolean isExceedScore() {
        boolean isReturn = false;
        float topicTotalScore = 0f;
        for (int i = 0; i < mList.size(); i++) {
            Topic tp = mList.get(i).getTopic();
            topicTotalScore = tp.getTopicPoint();
            int startNo = tp.getTopicBegin();
            int endNo = tp.getTopicEnd();
            String score = mList.get(i).getAnswer();
            if (StringUtil.parseFloat(score, 0f) > topicTotalScore) {
                MyToast.showShort(mContext, "第" + startNo + "~" + endNo + "题超出了总分，请重新录入");
                isReturn = true;
                break;
            }
        }
        return isReturn;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void showKeyboard(int position) {
        ArrayList<SubjectAnswer> tempList = mList;
        List<String> items = selectSubjectScore(position);
        String answer = tempList.get(position).getAnswer();
        // showAlterDialog(items, position, answer, tempList);
        showKeyboardDialog(items, position, answer, tempList);
    }

    private List<String> selectSubjectScore(int position) {
        List<String> items = null;
        float point = 0;
        int serialNum = mList.get(position).getSerialNumber();
        for (int i = 0; i < mTopics.size(); i++) {
            Topic t = mTopics.get(i);
            if (t.getTopicEnd() >= serialNum) {
                point = t.getTopicPoint();
                break;
            }
        }
        items = new ArrayList<String>();
        float score = 0.0f;
        for (; score <= point; ) {
            items.add(score + "");
            score += 0.5;
        }
        return items;
    }

    private void showKeyboardDialog(List<String> items, final int position,
                                    final String answer, final ArrayList<SubjectAnswer> tempList) {
        index = position;
        int serialNum = mList.get(index).getSerialNumber();
        int beginNo = mList.get(index).getTopic().getTopicBegin();
        int endNo = mList.get(index).getTopic().getTopicEnd();
        String title = null;
        if (beginNo != endNo) {
            title = " 第" + beginNo + "~" + endNo + "题：" + answer + " 分";
        } else {
            title = " 第" + serialNum + "题：" + answer + " 分";
        }
        mPopupWindow = new KeyboardWindow(mContext, this, title);
        if (answer.trim().equals("")) {
            mPopupWindow.setInputContent("0");
        } else {
            mPopupWindow.setInputContent(answer);
        }
        if (index == tempList.size() - 1) {
            mPopupWindow.setNextText("完成");
        } else if (index == 0) {
            mPopupWindow.setPreviewText("完成");
        }
        mPopupWindow.setNextListener(new KeyboardWindow.OnNextListener() {
            @Override
            public void next() {
                setKeyboardPositionAnswer(index);
                if (index < tempList.size() - 1) {
                    index += 1;
                    setPositionData(tempList);
                    String nextButtonStr = "下一题";
                    if (index == tempList.size() - 1) {
                        nextButtonStr = "完成";
                    }
                    mPopupWindow.setNextText(nextButtonStr);
                    if (index != 0) {
                        mPopupWindow.setPreviewText("上一题");
                    }
                } else {
                    mPopupWindow.dismiss();
                }
            }
        });
        mPopupWindow.setPreviewListener(new KeyboardWindow.OnPreviewListener() {
            @Override
            public void preview() {
                setKeyboardPositionAnswer(index);
                if (index > 0) {
                    index -= 1;
                    setPositionData(tempList);
                    String previewButtonStr = "上一题";
                    if (index == 0) {
                        previewButtonStr = "完成";
                    }
                    mPopupWindow.setPreviewText(previewButtonStr);
                    if (index != tempList.size() - 1) {
                        mPopupWindow.setNextText("下一题");
                    }
                } else {
                    mPopupWindow.dismiss();
                }
            }
        });
        mPopupWindow.showAtLocation(SubjectAnswerActivity.this.findViewById(R.id.subject_main),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void setPositionData(List<SubjectAnswer> answerList) {
        int serialNum2 = mList.get(index).getSerialNumber();
        String answer2 = answerList.get(index).getAnswer();
        int beginNo = mList.get(index).getTopic().getTopicBegin();
        int endNo = mList.get(index).getTopic().getTopicEnd();
        String title2 = null;
        if (beginNo != endNo) {
            title2 = " 第" + beginNo + "~" + endNo + "题：" + answer2 + " 分";
        } else {
            title2 = " 第" + serialNum2 + "题：" + answer2 + " 分";
        }
        mPopupWindow.setTitle(title2);
        if (answer2.trim().equals("")) {
            mPopupWindow.setInputContent("0.0");
        } else {
            mPopupWindow.setInputContent(answer2);
        }
    }

    private void setKeyboardPositionAnswer(final int position) {
        String currentAnswer = mPopupWindow.getScore() + "";
        mList.get(position).setAnswer(currentAnswer);
        mAdapter.notifyDataSetChanged();
        isUpdate = true;
        setHeaderScore();
        // TODO是否是修改后的按钮状态
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_subject_upload, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.subject_upload_summit:
                setStudentScore();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
